import pandas as pd


def recoding_ratings(recoding_path: str, df_ratings: pd.DataFrame,
                     user_sign: bool = True, item_sign: bool = True,
                     sort_phase=None):
    def recoding_in_list(cur_list: list):

        cur_set = list(set(cur_list))
        cur_set.sort()

        trans_dic = {}
        recoding_list = list()
        cur_index = 1

        for elem in cur_set:
            trans_dic[elem] = cur_index
            cur_index += 1

        for elem in cur_list:
            recoding_list.append(trans_dic[elem])

        return recoding_list

    if user_sign:
        user_list = df_ratings['userId'].tolist()
        user_recoding_list = recoding_in_list(user_list)
        df_ratings['userId'] = user_recoding_list

    if item_sign:
        item_list = df_ratings['itemId'].tolist()
        item_recoding_list = recoding_in_list(item_list)
        df_ratings['itemId'] = item_recoding_list

    if not sort_phase:
        df_ratings.sort_values(by=sort_phase, inplace=True)

    write_recoding_ratings(recoding_path, df_ratings)
    return df_ratings


def write_recoding_ratings(recoding_path: str, df_ratings: pd.DataFrame):
    recoding_file = open(recoding_path, 'w')
    ratings_num = df_ratings.shape[0]
    cur_index = 0
    for row in df_ratings.itertuples():
        info = '\t'.join([str(i) for i in list(row)[1:]])
        if cur_index < ratings_num - 1:
            info += '\n'
        recoding_file.write(info)
        cur_index += 1
    recoding_file.close()
